<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Admin extends CI_Controller {

    public function index($action = false, $id = false) {
		
        if (!$this->session->userdata('sessionAdmin'))
            redirect(base_url() . 'admin/login');

        $this->load->model("berita_model");
        switch ($action) {
            case "insert":
            case "update":
                $this->load->model("berita_model");
                $this->form_validation->set_rules('page', 'page', 'required');
                $this->form_validation->set_rules('judul', 'title', 'required');
                $this->form_validation->set_rules('judul_url', 'title url', 'required');
                $this->form_validation->set_rules('synopsis', 'content', 'required');
                $this->form_validation->set_rules('isi', 'full content', 'required');
                $this->form_validation->set_message('required', 'Field %s wajib di isi.');

                if ($this->input->post() && $this->form_validation->run()) {
                    $data['page'] = $this->input->post('page');
                    $data['judul'] = $this->input->post('judul');
                    $data['judul_url'] = $this->input->post('judul_url');
                    $data['synopsis'] = $this->input->post('synopsis');
                    $data['isi'] = $this->input->post('isi');
                    if ($this->input->post('id')) {
                        $data['id'] = $this->input->post('id');
                        $this->berita_model->updateBeritaById($data);
                        redirect(base_url() . "admin");
                    } else {
                        $this->berita_model->insertBerita($data);
                        redirect(base_url() . "admin");
                    }
                }
                $data = array();
                if ($id) {
                    $data['berita'] = $this->berita_model->getBeritaById($id);
                }
                $data['template']['nav'] = "essential/admin_header";
                $data['template']['content'] = 'berita/update';
                $data['template']['nosidebar'] = TRUE;
                $this->load->view('essential/template', $data);
                break;
            case "delete":
                if ($id) {
                    $this->berita_model->deleteBeritaById($id);
                }
                redirect(base_url() . "admin");
                break;
            default:
            	$this->load->library('pagination');
				
            	$limit			= 10;
            	
            	$data['berita'] = $this->berita_model->getBerita($limit, $id);
            	$count_news		= $this->berita_model->getCountBerita(); 
            	
            	$config['base_url']		= site_url('admin/index/news/');
				$config['total_rows']	= $count_news;
				$config['per_page']		= $limit;
				$config['uri_segment']	= 4;
		
				$this->pagination->initialize ( $config );
            	
				$data['paging']					= $this->pagination->create_links();
                $data['template']['nav']		= "essential/admin_header";
                $data['template']['content']	= 'berita/index';
                $data['template']['nosidebar']	= TRUE;
                
                $this->load->view('essential/template', $data);
                break;
        }
    }

    public function loginadmin($action = false, $id = false) {
        if (!$this->session->userdata('sessionAdmin'))
            redirect(base_url() . 'admin/login');

        $this->load->model("user_model");
        switch ($action) {
            case "insert":
            case "update":
                $this->form_validation->set_rules('username', 'Username', 'required');
                $this->form_validation->set_rules('password', 'Password', 'required|matches[repassword]');
                $this->form_validation->set_rules('repassword', 'Konfirmasi', 'required');
                $this->form_validation->set_message('required', 'Field %s wajib di isi.');
                $this->form_validation->set_message('matches', '%s tidak sama dengan konfirmasi.');

                if ($this->input->post() && $this->form_validation->run()) {
                    $postId = $this->input->post('id');
                    $postUsername = $this->input->post('username');
                    $postPassword = $this->input->post('password');
                    $postStatus = $this->input->post('status');
                    if ($postId) {
                        $data['id'] = $postId;
                        $data['username'] = $postUsername;
                        $data['password'] = $this->encode_password($postPassword);
                        $data['status'] = $postStatus;
                        if ($this->user_model->updateUserById($data))
                            redirect(base_url() . "admin");
                    } else {
                        $data['username'] = $postUsername;
                        $data['password'] = $this->encode_password($postPassword);
                        $data['status'] = $postStatus;
                        if ($this->user_model->insertUser($data))
                            redirect(base_url() . "admin");
                    }
                }
                $data = array();
                if ($id) {
                    $data['user'] = $this->user_model->getUserById($id);
                }
                $this->template->write('title', 'Form User');
                $this->template->write_view('content', 'admin/update', $data);
                $this->template->render();
                break;
            case "delete":
                if ($id) {
                    $this->user_model->deleteUserById($id);
                }
                redirect(base_url() . "admin/user");
                break;
            default:
                $data['user'] = $this->user_model->getUser();
                $this->template->write('title', 'List User');
                $this->template->write_view('content', 'admin/index', $data);
                $this->template->render();
                break;
        }
    }

    public function member($action = false, $id = false) {
        if (!$this->session->userdata('sessionAdmin'))
            redirect(base_url() . 'admin/login');

        $this->load->model("member_model");
        switch ($action) {
            case "insert":
            case "update":
                $this->form_validation->set_rules('username', 'Username', 'required');
                $this->form_validation->set_rules('password', 'Password', 'required|matches[repassword]');
                $this->form_validation->set_rules('repassword', 'Konfirmasi', 'required');
                $this->form_validation->set_message('required', 'Field %s wajib di isi.');
                $this->form_validation->set_message('matches', '%s tidak sama dengan konfirmasi.');

                if ($this->input->post() && $this->form_validation->run()) {
                    $postId = $this->input->post('id');
                    $postUsername = $this->input->post('username');
                    $postPassword = $this->input->post('password');
                    $postStatus = $this->input->post('status');
                    if ($postId) {
                        $data['id'] = $postId;
                        $data['username'] = $postUsername;
                        $data['password'] = $this->encode_password($postPassword);
                        $data['status'] = $postStatus;
                        if ($this->member_model->updateMemberById($data))
                            redirect(base_url() . "admin/member");
                    } else {
                        $data['username'] = $postUsername;
                        $data['password'] = $this->encode_password($postPassword);
                        $data['status'] = $postStatus;
                        if ($this->member_model->insertMember($data))
                            redirect(base_url() . "admin/member");
                    }
                }
                $data = array();
                if ($id) {
                    $data['member'] = $this->member_model->getMemberById($id);
                }
                $this->template->write('title', 'Form Member');
                $this->template->write_view('content', 'admin/memberform', $data);
                $this->template->render();
                break;
            case "delete":
                if ($id) {
                    $this->member_model->deleteMemberById($id);
                }
                redirect(base_url() . "admin/member");
                break;
            case "approval":
                if ($id) {
                    $param['uid'] = $id;
                    $param['status'] = 2;
                    $this->member_model->updateMemberById($param);
                }
                redirect(base_url() . "admin/member");
                break;
            default:
                $data['member'] = $this->member_model->getMember();
                $data['template']['nav'] = "essential/admin_header";
                $data['template']['content'] = 'admin/member';
                $data['template']['nosidebar'] = TRUE;
                $this->load->view('essential/template', $data);
                break;
        }
    }

    public function login() {

        if ($this->input->post()) {
            $data['username'] = $this->input->post('username', TRUE);
            $data['password'] = $this->encode_password($this->input->post('password', TRUE));
            $this->load->model("user_model");
            $users = $this->user_model->getUserLogin($data);

            if ($users != FALSE) {
                $login['sessionAdmin'] = TRUE;

                $this->session->set_userdata($login);
				
                redirect(site_url('admin/index'));
            } else {
                $data['err'] = 'Wrong username/password';
            }
        }

        $data ['template'] ['nav'] = "essential/login_header";
        $data ['template'] ['content'] = 'admin/login';
        $data ['template'] ['nosidebar'] = TRUE;

        $this->load->view('essential/template', $data);
    }

    public function logout() {
        $login['sessionAdmin'] = false;

        $this->session->unset_userdata($login);
        redirect(base_url() . 'admin/login');
    }

    protected function encode_password($string = NULL) {
        if ($string == NULL) {
            return NULL;
        }
        $string .= $this->config->item('encryption_key');
        return sha1($string);
    }

    public function approve_register($action = false, $id = false) {

        if (!$this->session->userdata('sessionAdmin'))
            redirect(base_url() . 'admin/login');

        $this->load->model("register_model");
        if ($action == "approve") {
            if ($id) {
            	
                $dataUser = $this->register_model->getRegUser($id, 1);
                
                if($dataUser) {
                	
                	$member['uid']			= "CBC-" . date("ymdHis");
                	$member['email']		= $dataUser['email'];
                	$member['pin']			= $this->random();
                	$member['referral_uid']	= $dataUser['referral_uid'];
                	
                	$this->register_model->updateRegUser($id);
                	$add = $this->register_model->addUserMember($member);

                	if($add) {
                		
                		$treeBuild = $this->_buildTree($member);
                		
                		if($treeBuild == TRUE) {
                			
                			$mailMsg = "Dear Valued Customer \n 
										Akun anda sudah aktif. silahkan klik link untuk login. " . base_url() . "memberlogin" .
					                        "\n\nUsername : " . $member['uid'] . "\nPassword : " . $member['pin'];
                			
							$this->load->library('email');
							$this->email->from('cbcsystem@yahoo.com', 'CBCSystem');
							$this->email->to($dataUser['email']);
							$this->email->subject('Success Register.');
							$this->email->message($mailMsg);
							//$this->email->send();
							//echo $this->email->print_debugger();
                			//error_log($mailMsg . "\n" , 3, '/tmp/mail');
                		}
                	}
                }
            }
            redirect(base_url() . "admin/approve_register/list/");
        }
        
        $this->load->library('pagination');
        
        $limit			= 10;
		$data['user']	= $this->register_model->getRegList($limit, $id);
		$count_user		= $this->register_model->countRegList();
            	
		$config['base_url']		= site_url( 'admin/approve_register/list/' );
		$config ['total_rows']	= $count_user;
		$config ['per_page']	= 1;
		$config ['uri_segment'] = 4;
            	
		$this->pagination->initialize ( $config );
        
        $data['paging']					= $this->pagination->create_links();
        $data['template']['nav']		= "essential/admin_header";
		$data['template']['content']	= 'admin/approve';
		$data['template']['nosidebar']	= TRUE;
		
		$this->load->view('essential/template', $data);
    }
    
    public function cashout($action = false, $id = false) {
		
		if (! $this->session->userdata ( 'sessionAdmin' ))
			redirect ( base_url () . 'admin/login' );

		$this->load->model("tree_model");	
		
		if($action == 'approve') {
			
			$aParams = explode('~', $id);
			
			//echo urldecode($aParams[1]); print_r($aParams); exit;
			
			if(isset($aParams[0]) && isset($aParams[1])) {
				
				$this->tree_model->approveCashout($aParams[0], urldecode($aParams[1]));
				
			}
			
			redirect(site_url('admin/cashout'));
		}
		
		$this->load->library('pagination');

		$id				= (int) $id;
		$limit			= 10;
		$data['user']	= $this->tree_model->getCashoutRequest($id, $limit);
		$count_user		= $this->tree_model->countCashoutRequest($id, $limit);
            	
		$config['base_url']		= site_url( 'admin/cashout/list/' );
		$config['total_rows']	= $count_user;
		$config['per_page']		= 1;
		$config['uri_segment']	= 4;
            	
		$this->pagination->initialize ( $config );
        
        $data['paging']					= $this->pagination->create_links();
        $data['template']['nav']		= "essential/admin_header";
		$data['template']['content']	= 'admin/cashout';
		$data['template']['nosidebar']	= TRUE;
		
		$this->load->view('essential/template', $data);
	}

    private function random($len = 8) {
        $chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $token = '';
        for ($i = 0; $i < $len - 1; $i++)
            $token .= $chars [mt_rand(0, strlen($chars))];
        return $token;
    }
    
    
    /* here's the magic, sort of */
    private function _buildTree($member = array()) {

    	$node			= array();
    	$node['root']	= $member['uid'];
    	$node['parent']	= FALSE;
    	$node['uid']	= $member['uid'];
    	$node['lft']	= 1;
    	$node['rgt']	= 2;
    	$node['lvl']	= 0;
    	$node['price']	= BASE_PRICE * BASE_PERCENTAGE;
    	
    	$this->load->model('tree_model');
    	
    	if(isset($member['referral_uid']) && !empty($member['referral_uid'])) {
    		
    		$getParent = $this->tree_model->getNode($member['referral_uid']);
    		
    		if($getParent != FALSE) {
    			
    			$node['root']	= $getParent['root'];
    			$node['parent']	= $member['referral_uid'];
    			$node['lft']	= $getParent['lft'] + 1;
    			$node['rgt']	= $getParent['lft'] + 2;
    			$node['lvl']	= $getParent['lvl'] + 1;
    			$node['pNode']	= $getParent;
    			
    			$tree = $this->tree_model->addBranch($node);
    			
    			if($tree == TRUE) {
    				
    				// add into cashout, select from all ascend, lft < lft self & rgt > rgt self
    				$ancestors = $this->tree_model->selectAncestor($node);
    				
    				foreach($ancestors as $ancestor) {
    					
    					$addNode = array(
    									'uid'			=> $node['uid'],
    									'recipient'		=> $ancestor['uid'],
    									'price'			=> BASE_PRICE * BASE_PERCENTAGE,
    									'date_created'	=> date('Y-m-d H:i:s'),
    									'status'		=> 0
    								);
    								
    					$this->tree_model->addCashout($addNode);
    					
    				}
    			}
    			
    		} else {
    			
    			return FALSE;
    			
    		}
    		
    	} else {
    		
    		return $this->tree_model->addNode($node);
    		    		
    	}
    }

}
